use std::fs::File;
use std::io::BufReader;
use std::io::Read;

use chrono::NaiveDateTime;

#[allow(dead_code)]
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Article {
    id: i32,
    title: String,

    #[sqlx(rename = "categoryId")]
    category_id: Option<i32>,
    summary: String,
    path: String,
    deleted: bool,
    #[sqlx(rename = "createOn")]
    create_on: NaiveDateTime,
    #[sqlx(rename = "createBy")]
    create_by: String,
    #[sqlx(rename = "modifyOn")]
    modify_on: NaiveDateTime,
    #[sqlx(rename = "modifyBy")]
    modify_by: String,
}

impl Article {
    pub async fn read_file(&self) -> String {
        println!("文件路径 {}。", &self.path);
        let file = match File::open(&self.path) {
            Ok(file) => {
                println!("成功找到文件。");
                file
            }
            Err(err) => {
                println!("无法打开文件: {}", err);
                return String::from("Sorry， 找不到此博客。");
            }
        };
        let mut buf_reader = BufReader::new(file);
        let mut contents = String::new();
        let _ = buf_reader.read_to_string(&mut contents);
        contents
    }

    pub fn get_info(self) -> (i32, String, NaiveDateTime) {
        (self.id, self.title, self.create_on)
    }
}
